/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unipiloto.edu.co.generador_reportes.service.admin;

import unipiloto.edu.co.generador_reportes.service.tracker.ServiceLocator;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.osgi.framework.BundleContext;

/**
 *
 * @author David
 */
@WebServlet(name = "AddReportServlet", urlPatterns = "/addReport")
@MultipartConfig
public class AddReportServlet extends HttpServlet {

    private static final Logger logger = Logger.getLogger("unipiloto.edu.co");    

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Agregar Reporte</title>");
        out.println("</head>");
        out.println("<body bgcolor=white>");
        try {

            ServiceLocator locator = new ServiceLocator(getBundleContext());
            try {
                locator.getReportGeneratorService(-1);
                Part partReportFile = request.getPart("reportFile");
                //logger.log(Level.INFO, "Part: {0}", partReportFile.getName());
                InputStream is = request.getPart(partReportFile.getName()).getInputStream();
                int i = is.available();
                byte[] b = new byte[i];
                is.read(b);
                is.close();
                //logger.log(Level.INFO, "Tama\u00f1o reporte: {0}", b.length);
                String fileName = getFileName(partReportFile);
                //logger.log(Level.INFO, "Nombre reporte: {0}", fileName);
                Part partReportName = request.getPart("reportName");
                Scanner s = new Scanner(partReportName.getInputStream());
                String reportName = s.nextLine();    // read filename from stream

                if (locator.getReportGeneratorService(-1).addReport(reportName, fileName, b)) {
                    out.println("Reporte guardado: " + reportName);
                    out.println("<h3>Reporte agregado!</h3>");
                } else {
                    out.println("No se ha podido guardar el reporte. Intente de nuevo");
                }                
            } catch (ServiceLocator.ServiceUnavailableException e) {
                out.println("El servicio no se encuentra disponible...");
            }
        } catch (Exception ex) {
            ex.printStackTrace(out);
        } finally {
            out.close();
        }
        out.println("</body>");
        out.println("</html>");
    }

    private BundleContext getBundleContext() {
        return BundleContext.class.cast(getServletConfig().getServletContext().getAttribute("osgi-bundlecontext"));
    }

    private String getFileName(Part part) {
        String partHeader = part.getHeader("content-disposition");
        logger.log(Level.INFO, "Part Header = {0}", partHeader);
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}
